package com.ckd.flyingtrip.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.fragment.BuycarFragment;
import com.ckd.flyingtrip.fragment.CarentalFragment;
import com.ckd.flyingtrip.fragment.HomeFragment;
import com.ckd.flyingtrip.fragment.MeFragment;
import com.ckd.flyingtrip.javabean.UserInfoBean;
import com.ckd.flyingtrip.utils.AppUtils;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainNewActivity extends BaseActivity {

    @BindView(R.id.activity_main_frameLayout)
    FrameLayout frameLayout;
    @BindViews({R.id.activity_main_tab1_imageView, R.id.activity_main_tab2_imageView, R.id.activity_main_tab3_imageView, R.id.activity_main_tab4_imageView})
    List<ImageView> imageViews;
    @BindViews({R.id.activity_main_tab1_textView, R.id.activity_main_tab2_textView, R.id.activity_main_tab3_textView, R.id.activity_main_tab4_textView})
    List<TextView> textViews;

    private int[] tabs = {R.mipmap.activity_main_tab_icon1, R.mipmap.activity_main_tab_icon2, R.mipmap.activity_main_tab_icon3, R.mipmap.activity_main_tab_icon4};
    private int[] not_tabs = {R.mipmap.activity_main_tabnot_icon1, R.mipmap.activity_main_tabnot_icon2, R.mipmap.activity_main_tabnot_icon3, R.mipmap.activity_main_tabnot_icon4};

    private HomeFragment homeFragment;
    private BuycarFragment buycarFragment;
    private CarentalFragment carentalFragment;
    private MeFragment meFragment;

    private int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initData();
//        initView();

    }

    private void initData() {
        homeFragment = new HomeFragment();
        volleyUserInfo();
    }

    private void volleyUserInfo() {
        long startTime = System.currentTimeMillis();
        StringRequest request = new StringRequest(Request.Method.POST, Constants.QINGQIUGERENXINXI, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("用户信息", s);
                long endTime = System.currentTimeMillis();
                Log.i("用户信息请求时间", endTime - startTime + "");
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    switch (code) {
                        case "0":
                            toast(msg);
                            break;
                        case "1":
                            JSONObject dataInfo = json.getJSONObject("data");
                            String data = json.getString("data");
                            UserInfoBean userInfoBean = new Gson().fromJson(data, UserInfoBean.class);
                            Constants.CITYID = userInfoBean.getUserArea();
                            BcUtils.setUserInfo(userInfoBean);
                            BcUtils.setUid(userInfoBean.getUserId());
                            BcUtils.setToken(userInfoBean.getToken());
                            BcUtils.setPhone(userInfoBean.getUserPhone());
                            BcUtils.setSignState(userInfoBean.getUserState());
                            BcUtils.setuserRent(userInfoBean.getUserRent());
                            BcUtils.setuserDeposit(userInfoBean.getUserDeposit());
                            BcUtils.setbindingElectricBicycle(userInfoBean.getBindingElectricBicycle());
                            HomeFragment.userStart = Integer.parseInt(userInfoBean.getUserState());
                            initView();
                            initCityJudge(userInfoBean.getUserArea());
                            break;
                        case "2":
                            startActivity(new Intent(MainNewActivity.this, UserLogInActivity.class));
                            Tools.closeLogIN(MainNewActivity.this);
                            finish();
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userPhone", BcUtils.getUserInfo().getUserPhone());
                    json_url.put("token", BcUtils.getToken());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initCityJudge(String userArea) {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.judgerentcarservice, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("获取该城市的最大租用电池数", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        String data = json.getString("data");
                        String cityBatteryMax = new JSONObject(data).getString("cityBatteryMax");
                        BcUtils.setCityBatteryMax(cityBatteryMax);
                    } else {
                        Tools.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userArea", userArea);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initView() {
        initTab();
        checkTab(index);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.activity_main_frameLayout, homeFragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    private void checkTab(int index) {
        textViews.get(index).setTextColor(ContextCompat.getColor(this, R.color.color_f3800f));
        imageViews.get(index).setImageResource(tabs[index]);
    }

    private void initTab() {
        for (int i = 0; i < textViews.size(); i++) {
            textViews.get(i).setTextColor(ContextCompat.getColor(this, R.color.color_333));
            imageViews.get(i).setImageResource(not_tabs[i]);
        }
    }

    @OnClick({R.id.activity_main_tab1, R.id.activity_main_tab2, R.id.activity_main_tab3, R.id.activity_main_tab4})
    public void onViewClicked(View view) {
        hideAll();
        initTab();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        switch (view.getId()) {
            case R.id.activity_main_tab1:
                index = 0;
                fragmentTransaction.show(homeFragment);
                checkTab(index);
                break;
            case R.id.activity_main_tab2:
                index = 1;
                if (buycarFragment == null) {
                    buycarFragment = new BuycarFragment();
                    fragmentTransaction.add(R.id.activity_main_frameLayout, buycarFragment);
                }
                fragmentTransaction.show(buycarFragment);
                checkTab(index);
                break;
            case R.id.activity_main_tab3:
                index = 2;
                if (carentalFragment == null) {
                    carentalFragment = new CarentalFragment();
                    fragmentTransaction.add(R.id.activity_main_frameLayout, carentalFragment);
                }
                fragmentTransaction.show(carentalFragment);
                checkTab(index);
                break;
            case R.id.activity_main_tab4:
                index = 3;
                if (meFragment == null) {
                    meFragment = new MeFragment();
                    fragmentTransaction.add(R.id.activity_main_frameLayout, meFragment);
                }
                fragmentTransaction.show(meFragment);
                checkTab(index);
                break;
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    private void hideAll() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (homeFragment != null)
            fragmentTransaction.hide(homeFragment);
        if (buycarFragment != null)
            fragmentTransaction.hide(buycarFragment);
        if (carentalFragment != null)
            fragmentTransaction.hide(carentalFragment);
        if (meFragment != null)
            fragmentTransaction.hide(meFragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean isExit;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            isExit = false;
        }
    };

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            System.exit(0);
        }
    }
}
